package com.guozcc.bootweb.platform.initializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * UDP监听端口demo
 */
@Component
public class UdpServer implements ApplicationRunner {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Override
    public void run(ApplicationArguments args) throws Exception {

        new Thread(() -> {
            MDC.put("traceId", "UDP监听8083端口-"+System.currentTimeMillis());
            try {
                DatagramSocket datagramSocket = new DatagramSocket(7001);
                byte[] buff = new byte[1024];
                while (true){
                    DatagramPacket datagramPacket = new DatagramPacket(buff,buff.length);
                    datagramSocket.receive(datagramPacket);
                    byte[] data = datagramPacket.getData();
                    execute(data);
                }
            }catch (Exception e){
                log.error("",e);
            }
        }).start();
        log.info("UDP监听7001口完成");
    }

    @Transactional(rollbackFor = Exception.class)
    public void execute(byte[] data) throws IOException {
        log.info("7001UDP收到的字节："+data.length);
    }

}
